/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 *
 * @author spthanh
 */
public class PrepareStatement_Example {
    public static void main(String[] args){
        try{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks", "sa", "123");

            //Initialize jdbc odbc bridge driver and load Driver
            //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            //Create connection 
            //Connection con = DriverManager.getConnection("jdbc:odbc:MyDataSource", "sa", "123456");
            //Query
            String query = "SELECT * FROM Person.Address WHERE City  LIKE ?";
            //Prepare Statement
            PreparedStatement pstmt =  con.prepareStatement(query);
            //String inputParam = "London";
            pstmt.setString(1,"%London%");
            //Get result set
            ResultSet rs = pstmt.executeQuery();
            //Traverse the result set
            while(rs.next()){
                System.out.println("AddressID:" + rs.getInt("AddressID"));
                System.out.println("Address Line 1:" + rs.getString("AddressLine1"));
                System.out.println("City:" + rs.getString("City"));
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
